//leetcode 79 单词搜索
public class Test3 {
    boolean[][] vis;
    int m, n, pos;
    char[] arr;
    int[] dx, dy;
    public boolean exist(char[][] board, String word) {
        m = board.length;
        n = board[0].length;
        vis = new boolean[m][n];
        dx = new int[]{0, 0, 1, -1};
        dy = new int[]{1, -1, 0, 0};
        arr = word.toCharArray();
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (board[i][j] == arr[0]) {
                    vis[i][j] = true;
                    if (dfs(board, i, j, 1)) return true;
                    vis[i][j] = false;
                }
            }
        }

        return false;
    }

    private boolean dfs(char[][] board, int i, int j, int pos) {
        if (pos == arr.length) return true;
        for (int k = 0; k < 4; k++) {
            int x = i + dx[k];
            int y = j + dy[k];
            if (x >= 0 && y >= 0 && y < n && x < m && !vis[x][y] && board[x][y] == arr[pos]) {
                vis[x][y] = true;
                if (dfs(board, x, y, pos + 1)) return true;
                vis[x][y] = false;
            }
        }

        return false;
    }

}
